from typing import Optional

from fastapi import APIRouter, Depends, status
from pydantic import BaseModel

from conf import variable
from conf.mysql_cnx import MysqlCnxPool
from dependencies import get_current_user
from service import user_report
from service.user import UserModel
from service.user_report import Report, ReportStatus

router = APIRouter(prefix=variable.CONTEXT_PATH + '/report',
                   tags=['report'],
                   dependencies=[Depends(get_current_user)])


class FindReportByIdItem(BaseModel):
    report_id: int


@router.post('/find_report_by_id')
async def find_report_by_id(item: FindReportByIdItem):
    session = MysqlCnxPool().get_session()
    report = session.query(Report).filter(Report.id == item.report_id).first()

    payload = {'finding': report.finding, 'impression': report.impression,
               'comment': report.comment, 'label_ids': report.label_ids}
    return {'code': status.HTTP_200_OK, 'message': '', 'payload': payload}


@router.post('/find_next_spare_report')
async def find_next_spare_report(user: UserModel = Depends(get_current_user)):
    report = user_report.find_next_spare_report(user.id)

    return {'code': status.HTTP_200_OK, 'message': '', 'payload': report}


class SaveReportItem(BaseModel):
    report_id: int
    label_ids: str
    comment: Optional[str] = None


@router.post('/save_report')
async def save_report(item: SaveReportItem):
    session = MysqlCnxPool().get_session()
    report = session.query(Report).filter(Report.id == item.report_id).first()
    report.label_ids = item.label_ids
    report.comment = item.comment
    report.status = ReportStatus.COMPLETED
    session.commit()

    return {'code': status.HTTP_200_OK, 'message': '', 'payload': {}}


class FindUserReportListItem(BaseModel):
    page_size: int
    page_num: int


@router.post('/find_user_report_list')
async def find_user_report_list(item: FindUserReportListItem,
                                user: UserModel = Depends(get_current_user)):
    data_list, total = user_report.find_user_report_list(user.id,
                                                         item.page_size,
                                                         item.page_num)
    payload = {'data_list': data_list, 'total': total}
    return {'code': status.HTTP_200_OK, 'message': '', 'payload': payload}
